package com.pine.app.module.security.core.authorize.metadataSource;

import com.pine.app.module.security.core.matcher.AntPathRequestMatcher;
import com.pine.app.module.security.core.matcher.RequestMatcher;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MultiValueMap;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author xiaoyuan
 * @create 2020/3/23 15:55
 **/
@AllArgsConstructor
@NoArgsConstructor
@Getter
public class DefaultSecurityMetadataSource implements SecurityMetadataSource {

    private SecurityLoadMethodDataSource securityLoadMethodDataSource;


    @Autowired
    public void setSecurityLoadMethodDataSource(SecurityLoadMethodDataSource securityLoadMethodDataSource) {
        this.securityLoadMethodDataSource = securityLoadMethodDataSource;
    }

    @Override
    public Map<RequestMatcher, List<ConfigAttribute>> getConfig() {
        Map<RequestMatcher, List<ConfigAttribute>> result = new HashMap<>();
        MultiValueMap<String, String> valueMap = securityLoadMethodDataSource.getMethodDataSource();
        if (valueMap != null && valueMap.size() > 0) {
            Set<String> set = valueMap.keySet();
            set.forEach(s -> {
                List<ConfigAttribute> list = new ArrayList<>();
                List<String> list1 = valueMap.get(s);
                list1.forEach(s1 -> {
                    s1 = s1.replaceAll(" ","");
                    String name =( s1.contains("(")?s1.substring(0, s1.indexOf("(")):s1).trim();
                    PermissionType type = PermissionType.fromName(name).orElse(null);
                    if (type != null) {
                        if (s1.contains(",")) {
                            String[] s2 = s1.substring(s1.indexOf("(")+1,s1.length()-1).split(",");
                            for (int i = 0; i < s2.length; i++) {
                                list.add(new DefualtConfigAttribute(name + "(" + s2[i].trim() + ")",
                                        type));
                            }
                        } else {
                            list.add(new DefualtConfigAttribute(s1, type));
                        }
                    }

                });
                if(!CollectionUtils.isEmpty(list)){
                    result.put(new AntPathRequestMatcher(s), list);
                }
            });
        }
        return result;
    }

    @Override
    public List<ConfigAttribute> getConfigAttribute(HttpServletRequest request) {
        return null;
    }

    @Override
    public void setConfig(Map<RequestMatcher, List<ConfigAttribute>> matcherListMap) {

    }
}
